package logic

import (
	"context"
	"fmt"
	"rent/models"

	"rent/rentrpc/internal/svc"
	"rent/rentrpc/rentrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CollectAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCollectAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CollectAddLogic {
	return &CollectAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CollectAddLogic) CollectAdd(in *rentrpc.CollectAddRequest) (*rentrpc.CollectAddResponse, error) {
	// todo: add your logic here and delete this line
	var commodity models.Commodity
	models.DB.Where("id=?", in.CommodityId).Find(&commodity)
	if commodity.ID == 0 {
		return nil, fmt.Errorf("收藏的商品不存在")
	}
	var collect models.Collect
	models.DB.Where("commodity_id=?", in.CommodityId).Find(&collect)
	if collect.CommodityId != 0 {
		return nil, fmt.Errorf("商品已经收藏")
	}
	collect = models.Collect{
		UserId:      int(in.UserId),
		CommodityId: int(in.CommodityId),
	}
	models.DB.Create(&collect)
	return &rentrpc.CollectAddResponse{
		CollectId: int64(collect.ID),
	}, nil
}
